package br.com.danieljr.crowdmap.modelos;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class Localizacao implements LocationListener {
	private double altitude, latitude, longitude;
	private float precisao;
	private String provedor;
	private LocationManager LM;
	private Context contexto;

	public Localizacao(Context c) {
		contexto = c;
		LM = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
	}

	public void atualizaLocal() {
		if (LM.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			LM.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		} else {
			LM.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
					this);
		}
	}

	public void pararAtualizacao() {
		LM.removeUpdates(this);
	}

	public double getAltitude() {
		return altitude;
	}

	public double getLatitude() {
		return latitude;
	}

	public double getLongitude() {
		return longitude;
	}

	public float getPrecisao() {
		return precisao;
	}

	public String getProvedor() {
		return provedor;
	}

	@SuppressWarnings("finally")
	public String getNomeLocalizacao() {
		String resp = "";
		try {
			Geocoder geocoder;
			List<Address> addresses;
			geocoder = new Geocoder(contexto, Locale.getDefault());
			addresses = geocoder.getFromLocation(latitude, longitude, 1);
			String address = addresses.get(0).getAddressLine(0);
			String city = addresses.get(0).getAddressLine(1);
			String country = addresses.get(0).getAddressLine(2);
			resp += country + ", " + city + ", " + address;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resp+="Desconhecido";
		} finally {
			return resp;
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		precisao = location.getAccuracy();
		altitude = location.getAltitude();
		provedor = location.getProvider();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
}